package com.example.minio.controller;


import com.example.minio.util.MinioUtil;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@AllArgsConstructor
public class minioController {
   private MinioUtil minioUtil;

    @PostMapping(value = "/upload")
    public ResponseEntity<Boolean> uploadFile(MultipartFile file, @RequestParam(required = false) String bucketName) {
        bucketName = StringUtils.hasLength(bucketName) ? bucketName : null;
        String objectName = minioUtil.getDatePath() + file.getOriginalFilename();
        boolean upload = minioUtil.upload(bucketName, objectName, file);
//        String viewPath = minioUtil.getPresignedObjectUrl(bucketName, objectName, 60, TimeUnit.SECONDS);
//        HashMap<String, String> objectInfo = new HashMap<>();
//        objectInfo.put("objectName", objectName);
//        //只能预览图片、txt等部分文件
//        objectInfo.put("viewPath", viewPath);
        return ResponseEntity.ok(upload);
    }

    @DeleteMapping(value = "/delete")
    public ResponseEntity<String> deleteByPath(@RequestParam(required = false) String bucketName, String objectName) {
        bucketName = StringUtils.hasLength(bucketName) ? bucketName : null;
        minioUtil.delete(bucketName, objectName);
        return ResponseEntity.ok("删除成功");
    }

    /**
     * 下载文件
     * @param bucketName 桶名称
     * @param objectName 对象名称
     * @param response  相应结果
     */
    @GetMapping("/download")
    public void downLoad(@RequestParam(required = false) String bucketName, String objectName, HttpServletResponse response) {
        bucketName = StringUtils.hasLength(bucketName) ? bucketName : null;
        // 获取文件
        minioUtil.downResponse(bucketName,objectName,response);
    }
}
